using System.Text.Json;

namespace DocumentCreationSystem.Models.Agentic
{
    /// <summary>
    /// Agentic请求模型
    /// </summary>
    public class AgenticRequest
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string UserId { get; set; } = string.Empty;
        public string ProjectId { get; set; } = string.Empty;
        public string UserInput { get; set; } = string.Empty;
        public AgenticMode Mode { get; set; } = AgenticMode.Autonomous;
        public Dictionary<string, object> Context { get; set; } = new();
        public List<string> Preferences { get; set; } = new();
        public DateTime CreatedAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// Agentic响应模型
    /// </summary>
    public class AgenticResponse
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string RequestId { get; set; } = string.Empty;
        public AgenticStatus Status { get; set; } = AgenticStatus.Processing;
        public string Message { get; set; } = string.Empty;
        public List<AgenticAction> Actions { get; set; } = new();
        public AutonomousPlan? Plan { get; set; }
        public ExecutionResult? Result { get; set; }
        public List<ProactiveSuggestion> Suggestions { get; set; } = new();
        public DateTime CreatedAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// Agentic会话模型
    /// </summary>
    public class AgenticSession
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string UserId { get; set; } = string.Empty;
        public string ProjectId { get; set; } = string.Empty;
        public AgenticStatus Status { get; set; } = AgenticStatus.Active;
        public AgentContext Context { get; set; } = new();
        public List<Goal> Goals { get; set; } = new();
        public AutonomousPlan? CurrentPlan { get; set; }
        public List<ExecutionResult> ExecutionHistory { get; set; } = new();
        public DateTime StartedAt { get; set; } = DateTime.Now;
        public DateTime? EndedAt { get; set; }
    }

    /// <summary>
    /// 用户意图模型
    /// </summary>
    public class UserIntent
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public IntentType Type { get; set; } = IntentType.Unknown;
        public string Description { get; set; } = string.Empty;
        public List<string> Keywords { get; set; } = new();
        public Dictionary<string, object> Parameters { get; set; } = new();
        public float Confidence { get; set; } = 0.0f;
        public List<ImplicitIntent> ImplicitIntents { get; set; } = new();
        public IntentContext Context { get; set; } = new();
        public DateTime AnalyzedAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 智能体上下文模型
    /// </summary>
    public class AgentContext
    {
        public string SessionId { get; set; } = string.Empty;
        public string UserId { get; set; } = string.Empty;
        public string ProjectId { get; set; } = string.Empty;
        public Dictionary<string, object> Environment { get; set; } = new();
        public ConversationHistory History { get; set; } = new();
        public UserProfile UserProfile { get; set; } = new();
        public ProjectContext ProjectContext { get; set; } = new();
        public List<ContextSnapshot> Snapshots { get; set; } = new();
        public DateTime LastUpdated { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 自主计划模型
    /// </summary>
    public class AutonomousPlan
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string SessionId { get; set; } = string.Empty;
        public Goal PrimaryGoal { get; set; } = new();
        public List<SubGoal> SubGoals { get; set; } = new();
        public List<AgenticTask> Tasks { get; set; } = new();
        public ExecutionStrategy Strategy { get; set; } = new();
        public ResourceAllocation ResourceAllocation { get; set; } = new();
        public List<PlanRisk> Risks { get; set; } = new();
        public TimeSpan EstimatedDuration { get; set; }
        public PlanStatus Status { get; set; } = PlanStatus.Draft;
        public DateTime CreatedAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 目标模型
    /// </summary>
    public class Goal
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string Description { get; set; } = string.Empty;
        public GoalType Type { get; set; } = GoalType.Primary;
        public GoalPriority Priority { get; set; } = GoalPriority.Medium;
        public List<string> SuccessCriteria { get; set; } = new();
        public Dictionary<string, object> Metrics { get; set; } = new();
        public GoalStatus Status { get; set; } = GoalStatus.NotStarted;
        public DateTime CreatedAt { get; set; } = DateTime.Now;
        public DateTime? TargetDate { get; set; }
    }

    /// <summary>
    /// 子目标模型
    /// </summary>
    public class SubGoal : Goal
    {
        public string ParentGoalId { get; set; } = string.Empty;
        public int Order { get; set; } = 0;
        public List<string> Dependencies { get; set; } = new();
        public float Progress { get; set; } = 0.0f;
    }

    /// <summary>
    /// Agentic任务模型
    /// </summary>
    public class AgenticTask
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string Name { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public TaskType Type { get; set; } = TaskType.Analysis;
        public TaskPriority Priority { get; set; } = TaskPriority.Medium;
        public List<string> Dependencies { get; set; } = new();
        public Dictionary<string, object> Parameters { get; set; } = new();
        public ResourceRequirement ResourceRequirement { get; set; } = new();
        public TimeSpan EstimatedDuration { get; set; }
        public TaskStatus Status { get; set; } = TaskStatus.Pending;
        public DateTime CreatedAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 执行策略模型
    /// </summary>
    public class ExecutionStrategy
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string Name { get; set; } = string.Empty;
        public StrategyType Type { get; set; } = StrategyType.Sequential;
        public Dictionary<string, object> Parameters { get; set; } = new();
        public List<ExecutionPhase> Phases { get; set; } = new();
        public QualityGate QualityGates { get; set; } = new();
        public RiskMitigation RiskMitigation { get; set; } = new();
        public float SuccessProbability { get; set; } = 0.0f;
    }

    /// <summary>
    /// 执行阶段模型
    /// </summary>
    public class ExecutionPhase
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string Name { get; set; } = string.Empty;
        public int Order { get; set; } = 0;
        public List<string> TaskIds { get; set; } = new();
        public PhaseType Type { get; set; } = PhaseType.Sequential;
        public Dictionary<string, object> Configuration { get; set; } = new();
        public TimeSpan EstimatedDuration { get; set; }
    }

    /// <summary>
    /// 主动建议模型
    /// </summary>
    public class ProactiveSuggestion
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public SuggestionType Type { get; set; } = SuggestionType.Optimization;
        public string Title { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public SuggestionPriority Priority { get; set; } = SuggestionPriority.Medium;
        public List<string> Benefits { get; set; } = new();
        public List<AgenticAction> Actions { get; set; } = new();
        public float ConfidenceScore { get; set; } = 0.0f;
        public DateTime CreatedAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// Agentic动作模型
    /// </summary>
    public class AgenticAction
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string Name { get; set; } = string.Empty;
        public ActionType Type { get; set; } = ActionType.ToolCall;
        public Dictionary<string, object> Parameters { get; set; } = new();
        public ActionStatus Status { get; set; } = ActionStatus.Pending;
        public string? Result { get; set; }
        public DateTime CreatedAt { get; set; } = DateTime.Now;
        public DateTime? ExecutedAt { get; set; }
    }

    /// <summary>
    /// 执行结果模型
    /// </summary>
    public class ExecutionResult
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string PlanId { get; set; } = string.Empty;
        public ExecutionStatus Status { get; set; } = ExecutionStatus.InProgress;
        public List<TaskResult> TaskResults { get; set; } = new();
        public PerformanceMetrics Metrics { get; set; } = new();
        public List<string> Achievements { get; set; } = new();
        public List<ExecutionIssue> Issues { get; set; } = new();
        public LearningData LearningData { get; set; } = new();
        public DateTime StartedAt { get; set; } = DateTime.Now;
        public DateTime? CompletedAt { get; set; }
    }

    /// <summary>
    /// 任务结果模型
    /// </summary>
    public class TaskResult
    {
        public string TaskId { get; set; } = string.Empty;
        public TaskStatus Status { get; set; } = TaskStatus.Pending;
        public string? Output { get; set; }
        public Dictionary<string, object> Metrics { get; set; } = new();
        public List<string> Errors { get; set; } = new();
        public TimeSpan Duration { get; set; }
        public DateTime CompletedAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 性能指标模型
    /// </summary>
    public class PerformanceMetrics
    {
        public TimeSpan TotalDuration { get; set; }
        public int TasksCompleted { get; set; } = 0;
        public int TasksFailed { get; set; } = 0;
        public float SuccessRate { get; set; } = 0.0f;
        public float EfficiencyScore { get; set; } = 0.0f;
        public float QualityScore { get; set; } = 0.0f;
        public Dictionary<string, double> CustomMetrics { get; set; } = new();
    }

    /// <summary>
    /// 学习数据模型
    /// </summary>
    public class LearningData
    {
        public string SessionId { get; set; } = string.Empty;
        public List<string> SuccessPatterns { get; set; } = new();
        public List<string> FailurePatterns { get; set; } = new();
        public Dictionary<string, float> SkillImprovements { get; set; } = new();
        public List<string> NewKnowledge { get; set; } = new();
        public UserFeedback? UserFeedback { get; set; }
        public DateTime CollectedAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 隐式意图模型
    /// </summary>
    public class ImplicitIntent
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string Description { get; set; } = string.Empty;
        public float Confidence { get; set; } = 0.0f;
        public List<string> Indicators { get; set; } = new();
        public DateTime DiscoveredAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 意图上下文模型
    /// </summary>
    public class IntentContext
    {
        public string SessionId { get; set; } = string.Empty;
        public Dictionary<string, object> Variables { get; set; } = new();
        public List<string> RecentActions { get; set; } = new();
        public DateTime Timestamp { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 对话历史模型
    /// </summary>
    public class ConversationHistory
    {
        public List<ConversationTurn> Turns { get; set; } = new();
        public Dictionary<string, object> Context { get; set; } = new();
        public DateTime StartedAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 对话轮次模型
    /// </summary>
    public class ConversationTurn
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string UserInput { get; set; } = string.Empty;
        public string AgentResponse { get; set; } = string.Empty;
        public UserIntent? Intent { get; set; }
        public DateTime Timestamp { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 用户档案模型
    /// </summary>
    public class UserProfile
    {
        public string UserId { get; set; } = string.Empty;
        public Dictionary<string, object> Preferences { get; set; } = new();
        public List<string> Skills { get; set; } = new();
        public Dictionary<string, float> Interests { get; set; } = new();
        public WorkingStyle WorkingStyle { get; set; } = new();
        public DateTime LastUpdated { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 工作风格模型
    /// </summary>
    public class WorkingStyle
    {
        public string PreferredPace { get; set; } = "Medium";
        public string CommunicationStyle { get; set; } = "Balanced";
        public List<string> PreferredTools { get; set; } = new();
        public Dictionary<string, object> Patterns { get; set; } = new();
    }

    /// <summary>
    /// 项目上下文模型
    /// </summary>
    public class ProjectContext
    {
        public string ProjectId { get; set; } = string.Empty;
        public string ProjectType { get; set; } = string.Empty;
        public Dictionary<string, object> Metadata { get; set; } = new();
        public List<string> RecentFiles { get; set; } = new();
        public ProjectStatus Status { get; set; } = ProjectStatus.Active;
    }

    /// <summary>
    /// 上下文快照模型
    /// </summary>
    public class ContextSnapshot
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public Dictionary<string, object> State { get; set; } = new();
        public string Trigger { get; set; } = string.Empty;
        public DateTime Timestamp { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 资源分配模型
    /// </summary>
    public class ResourceAllocation
    {
        public Dictionary<string, int> CpuAllocation { get; set; } = new();
        public Dictionary<string, long> MemoryAllocation { get; set; } = new();
        public Dictionary<string, int> ToolAllocation { get; set; } = new();
        public TimeSpan TimeAllocation { get; set; }
    }

    /// <summary>
    /// 计划风险模型
    /// </summary>
    public class PlanRisk
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string Description { get; set; } = string.Empty;
        public RiskLevel Level { get; set; } = RiskLevel.Medium;
        public float Probability { get; set; } = 0.0f;
        public float Impact { get; set; } = 0.0f;
        public List<string> MitigationStrategies { get; set; } = new();
    }

    /// <summary>
    /// 资源需求模型
    /// </summary>
    public class ResourceRequirement
    {
        public int CpuUnits { get; set; } = 1;
        public long MemoryMB { get; set; } = 100;
        public List<string> RequiredTools { get; set; } = new();
        public TimeSpan MaxDuration { get; set; }
    }

    /// <summary>
    /// 质量门控模型
    /// </summary>
    public class QualityGate
    {
        public string Name { get; set; } = string.Empty;
        public List<QualityCriteria> Criteria { get; set; } = new();
        public float MinScore { get; set; } = 0.7f;
        public bool IsRequired { get; set; } = true;
    }

    /// <summary>
    /// 质量标准模型
    /// </summary>
    public class QualityCriteria
    {
        public string Name { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public float Weight { get; set; } = 1.0f;
        public float MinValue { get; set; } = 0.0f;
    }

    /// <summary>
    /// 风险缓解模型
    /// </summary>
    public class RiskMitigation
    {
        public List<MitigationStrategy> Strategies { get; set; } = new();
        public Dictionary<string, object> Contingencies { get; set; } = new();
        public MonitoringPlan MonitoringPlan { get; set; } = new();
    }

    /// <summary>
    /// 缓解策略模型
    /// </summary>
    public class MitigationStrategy
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string Name { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public List<string> Actions { get; set; } = new();
        public float Effectiveness { get; set; } = 0.0f;
    }

    /// <summary>
    /// 监控计划模型
    /// </summary>
    public class MonitoringPlan
    {
        public List<MonitoringPoint> Points { get; set; } = new();
        public TimeSpan CheckInterval { get; set; } = TimeSpan.FromMinutes(5);
        public List<string> Alerts { get; set; } = new();
    }

    /// <summary>
    /// 监控点模型
    /// </summary>
    public class MonitoringPoint
    {
        public string Name { get; set; } = string.Empty;
        public string Metric { get; set; } = string.Empty;
        public float Threshold { get; set; } = 0.0f;
        public string Action { get; set; } = string.Empty;
    }

    /// <summary>
    /// 执行问题模型
    /// </summary>
    public class ExecutionIssue
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string Description { get; set; } = string.Empty;
        public IssueType Type { get; set; } = IssueType.Warning;
        public IssueSeverity Severity { get; set; } = IssueSeverity.Medium;
        public string TaskId { get; set; } = string.Empty;
        public List<string> PossibleCauses { get; set; } = new();
        public List<string> SuggestedActions { get; set; } = new();
        public DateTime DetectedAt { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 用户反馈模型
    /// </summary>
    public class UserFeedback
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string SessionId { get; set; } = string.Empty;
        public FeedbackType Type { get; set; } = FeedbackType.General;
        public int Rating { get; set; } = 0;
        public string Comment { get; set; } = string.Empty;
        public Dictionary<string, object> Details { get; set; } = new();
        public DateTime ProvidedAt { get; set; } = DateTime.Now;
    }

    // 枚举定义
    public enum AgenticMode
    {
        Autonomous,     // 完全自主
        Collaborative,  // 协作模式
        Supervised,     // 监督模式
        Manual         // 手动模式
    }

    public enum AgenticStatus
    {
        Initializing,   // 初始化中
        Active,         // 活跃
        Processing,     // 处理中
        Waiting,        // 等待
        Completed,      // 完成
        Failed,         // 失败
        Paused         // 暂停
    }

    public enum IntentType
    {
        Unknown,        // 未知
        Creation,       // 创作
        Analysis,       // 分析
        Optimization,   // 优化
        Learning,       // 学习
        Planning,       // 规划
        Execution      // 执行
    }

    public enum GoalType
    {
        Primary,        // 主要目标
        Secondary,      // 次要目标
        Supporting,     // 支持目标
        Maintenance    // 维护目标
    }

    public enum GoalPriority
    {
        Critical,       // 关键
        High,          // 高
        Medium,        // 中
        Low            // 低
    }

    public enum GoalStatus
    {
        NotStarted,     // 未开始
        InProgress,     // 进行中
        Completed,      // 已完成
        Failed,         // 失败
        Cancelled      // 已取消
    }

    public enum TaskType
    {
        Analysis,       // 分析
        Creation,       // 创建
        Modification,   // 修改
        Validation,     // 验证
        Optimization,   // 优化
        Communication  // 沟通
    }

    public enum TaskPriority
    {
        Urgent,         // 紧急
        High,          // 高
        Medium,        // 中
        Low            // 低
    }

    public enum TaskStatus
    {
        Pending,        // 待处理
        InProgress,     // 进行中
        Completed,      // 已完成
        Failed,         // 失败
        Cancelled,      // 已取消
        Blocked        // 阻塞
    }

    public enum StrategyType
    {
        Sequential,     // 顺序执行
        Parallel,       // 并行执行
        Adaptive,       // 自适应
        Hybrid         // 混合模式
    }

    public enum PhaseType
    {
        Sequential,     // 顺序阶段
        Parallel,       // 并行阶段
        Conditional,    // 条件阶段
        Iterative      // 迭代阶段
    }

    public enum SuggestionType
    {
        Optimization,   // 优化建议
        Enhancement,    // 增强建议
        Warning,        // 警告建议
        Opportunity,    // 机会建议
        Learning       // 学习建议
    }

    public enum SuggestionPriority
    {
        Critical,       // 关键
        High,          // 高
        Medium,        // 中
        Low            // 低
    }

    public enum ActionType
    {
        ToolCall,       // 工具调用
        Analysis,       // 分析
        Decision,       // 决策
        Communication,  // 沟通
        Learning,       // 学习
        Planning       // 规划
    }

    public enum ActionStatus
    {
        Pending,        // 待执行
        InProgress,     // 执行中
        Completed,      // 已完成
        Failed,         // 失败
        Cancelled      // 已取消
    }

    public enum ExecutionStatus
    {
        NotStarted,     // 未开始
        InProgress,     // 进行中
        Completed,      // 已完成
        Failed,         // 失败
        Cancelled,      // 已取消
        Paused         // 暂停
    }

    public enum PlanStatus
    {
        Draft,          // 草稿
        Approved,       // 已批准
        InProgress,     // 执行中
        Completed,      // 已完成
        Failed,         // 失败
        Cancelled      // 已取消
    }

    public enum ProjectStatus
    {
        Active,         // 活跃
        Inactive,       // 非活跃
        Completed,      // 已完成
        Archived       // 已归档
    }

    public enum RiskLevel
    {
        Low,           // 低风险
        Medium,        // 中风险
        High,          // 高风险
        Critical       // 关键风险
    }

    public enum IssueType
    {
        Error,         // 错误
        Warning,       // 警告
        Information,   // 信息
        Performance    // 性能
    }

    public enum IssueSeverity
    {
        Low,           // 低严重性
        Medium,        // 中严重性
        High,          // 高严重性
        Critical       // 关键严重性
    }

    public enum FeedbackType
    {
        General,       // 一般反馈
        Quality,       // 质量反馈
        Performance,   // 性能反馈
        Usability,     // 可用性反馈
        Feature       // 功能反馈
    }
}
